package com.fc.util;

import com.google.common.collect.Maps;

import java.util.Map;

/**
 * Created by chenyan on 2016/5/12.
 */
public class Response<T> {

    private Result result = new Result<T>();
    private Map<String, Object> extraData = Maps.newHashMap();

    public Response<T> version(String version) {
        result.setVersion(version);
        return this;
    }

    public Response<T> fail() {
        result.setSuccess(false);
        return this;
    }

    public Response<T> success() {
        result.setSuccess(true);
        return this;
    }

    public Response<T> errCode(Integer errCode) {
        result.setErrCode(errCode);
        return this;
    }

    public Response<T> code(Integer code) {
        result.setCode(code);
        return this;
    }

    public Response data(T data) {
        result.setData(data);
        return this;
    }

    public Response<T> msg(String msg) {
        result.setMsg(msg);
        return this;
    }

    public Response total(Integer total){
        result.setTotal(total);
        return this;
    }

    public Response put(String key, Object value) {
        extraData.put(key, value);
        return this;
    }



    @Override
    public String toString() {
        if (extraData.isEmpty()) {
            return GsonUtils.toJson(result);
        } else {
            Map<String, Object> extraResult = GsonUtils.fromJson(GsonUtils.toJson(result), Map.class);
            extraResult.putAll(extraData);
            return GsonUtils.toJson(extraResult);
        }
    }

    private class Result<T> {

        private String version = "1.0";

        private boolean success;

        private Integer errCode;

        private String msg = "";

        private Integer total;

        private Integer code;

        private T data;

        public Result() {
        }

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public Integer getErrCode() {
            return errCode;
        }

        public void setErrCode(Integer errCode) {
            this.errCode = errCode;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public Integer getTotal() {
            return total;
        }

        public void setTotal(Integer total) {
            this.total = total;
        }
    }
}
